package com.lei.mvp_retrofitlibrary.http.token;

import com.blankj.utilcode.util.SPUtils;
import com.lei.mvp_retrofitlibrary.http.api.API;
import com.lei.mvp_retrofitlibrary.http.factory.BaseRetrofitFactory;
import com.lei.mvp_retrofitlibrary.http.product.BaseRetrofitProduct;
import com.lei.mvp_retrofitlibrary.http.url.BaseUrl;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @ProjectName : YoHuo001Java
 * @Author : 雷金泷
 * @Time : 2020/12/13 19:15
 * @Description : 文件描述
 */
public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response;
        if (SPUtils.getInstance().contains(BaseUrl.TOKEN_KEY)){
            response = chain.proceed(addToken(request,SPUtils.getInstance().getString(BaseUrl.TOKEN_KEY)));
        }else {
            response = chain.proceed(request);
        }
        if (response.code() == BaseUrl.TOKEN_NON){
            String newToken =createnewToken();
            SPUtils.getInstance().put(BaseUrl.TOKEN_KEY,newToken);
            response = chain.proceed(addToken(request,newToken));
        }
        return response;
    }
    private String createnewToken() throws IOException {
        return Objects.requireNonNull(BaseRetrofitFactory
                .create(API.class)
                .token("password","9417e1771571981321ef1701261c619a1db1eb12a1a41f51","")
                .execute()
                .body()).access_token;
    }
    private Request addToken(Request request, String token) {
        return request.newBuilder().addHeader("Authorization","bearer "+token).build();
    }
}
